import Clipboard from 'clipboard'

/** 原生 clipboard 用法
 *  var clipboard = new Clipboard('.btn')
 *  clipboard.on('success', function(e) {
      console.info('Action:', e.action);
      console.info('Text:', e.text);
      console.info('Trigger:', e.trigger);

      e.clearSelection();
    });

    clipboard.on('error', function(e) {
      console.error('Action:', e.action);
      console.error('Trigger:', e.trigger);
    });
 * */

/** jsx 用法
 *  const copyData = 'aaaa'
 *  render() {
 *    const directives = [
        { name: 'clipboard', value: copyData }
      ]
      return (
        <button {...{ directives }} on-success={ (e) => { console.log(e, 'copy success') } } on-error={ (e) => { console.log(e, 'copy error') }>{ copyData }</button>
      )
    }
 *
 *
*/

export default {
  directives: {
    'clipboard': {
      async bind(el, binding, vnode) {
        let { value } = binding
        const opt = {}

        if (value && typeof value === 'function') {
          value = await value()
        }

        // set string dynamically，return string
        if (/string|number/.test(typeof value)) {
          opt.text = () => `${value}`
        } else {
          throw new Error('Invalid value, please use a valid value!')
        }

        const clip = new Clipboard(el, opt)

        const { componentOptions, data } = vnode
        const listeners = componentOptions && componentOptions.listeners
        const on = data && data.on
        const events = listeners || on

        if (events && events instanceof Object && Object.keys(events).length) {
          Object.keys(events).map(cb => clip.on(cb, events[cb].fn || events[cb].fns))
        }

        el.clip = clip
      },

      update(el, binding) {
        el.clip.text = () => binding.value
        el.clip.action = () => binding.arg === 'cut' ? 'cut' : 'copy'
      },

      unbind(el) {
        if (el.clip && el.clip.destroy) {
          el.clip.destroy()
          delete el.clip
        }
      }
    }
  }
}
